package com.example.testcontract.fragments;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testcontract.R;
import com.example.testcontract.activity.ContactInformationActivity;
import com.example.testcontract.adapter.ContactAdapter;
import com.example.testcontract.bean.Contact;
import com.example.testcontract.bean.QuickLocationRightTool;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2014/9/18.
 * '*'索引代表列表到达最末端
 */
public class ContactFragment extends Fragment implements AdapterView.OnItemClickListener{
    //分组布局
    private LinearLayout titleLayout;
    //分组布局上显示的字母
    private TextView title;
    //联系人列表
    private ListView contactListView;
    //联系人列表适配器
    private ContactAdapter adapter;
    //右边快速查找栏
    private QuickLocationRightTool quickLocationRightTool;
    //字母
    String[] letter = new String[]{
        "#","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","*"
    };
    private String indexLetter = "";//用来存储存在的索引
    //用于进行字母表分组
    private AlphabetIndexer indexer;
    //用于存储手机上所有联系人
    private List<Contact> contacts = new ArrayList<Contact>();
    //字母表顺序规则
    private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //上次第一个可见元素，用于滚动时记录标识
    private int lastFirstVisibleItem = -1;

    public static ContactFragment newInstance() {
        return new ContactFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_contact, container, false);

        titleLayout = (LinearLayout) rootView.findViewById(R.id.title_layout);
        title = (TextView) rootView.findViewById(R.id.title);
        contactListView = (ListView) rootView.findViewById(R.id.contacts_list_view);

        //右边快速查找栏
        quickLocationRightTool = (QuickLocationRightTool) rootView.findViewById(R.id.quickLocation);
        quickLocationRightTool.setLetter(letter);
        quickLocationRightTool.setOnTouchingLetterChangedListener(new LetterListViewListener());

        adapter = new ContactAdapter(getActivity(), R.layout.contact_item, contacts);

        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor = getActivity().getContentResolver().query(uri, new String[]{"display_name", "sort_key",
                ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.Data.DATA15}, null, null, "sort_key");

        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(0);
                String sortKey = getSortKey(cursor.getString(1));
                String phoneNum = cursor.getString(2);
                Contact contact = new Contact();
                contact.setName(name);
                contact.setSortKey(sortKey);
                contact.setPhoneNumber(phoneNum);
                //取得头像
                byte[] str=cursor.getBlob(cursor.getColumnIndex(ContactsContract.Data.DATA15));
                if(str!=null) {
                    InputStream inputStream = new ByteArrayInputStream(str);
                    contact.setImage(BitmapFactory.decodeStream(inputStream));
                } else {
                    contact.setImage(BitmapFactory.decodeResource(getResources() ,R.drawable.launcher));
                }

                if (!indexLetter.contains(sortKey))
                    indexLetter += sortKey; //加入索引列表

                contacts.add(contact);
            }while (cursor.moveToNext());
        }
        getActivity().startManagingCursor(cursor);

        indexer = new AlphabetIndexer(cursor, 1, alphabet);
        adapter.setIndexer(indexer);
        if (contacts.size() > 0)
            setupContactsListView();

        return rootView;
    }

    int oldSection = 0;
    private void setupContactsListView(){
        contactListView.setAdapter(adapter);
        contactListView.setOnItemClickListener(this);
        contactListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int section = indexer.getSectionForPosition(firstVisibleItem);
                int nextSecPosition = indexer.getPositionForSection(section);
                if (firstVisibleItem != lastFirstVisibleItem) {
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout.getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(String.valueOf(alphabet.charAt(section)));

                    quickLocationRightTool.setChoose(section);           //滑动时右边字母查找栏字母颜色随之改变
                    if (section != oldSection) {
                        showIndex(alphabet.charAt(section) + "");
                    }
                    if (firstVisibleItem == totalItemCount - visibleItemCount) {
                        section++;
                        quickLocationRightTool.setChoose(section);           //滑动时右边字母查找栏字母颜色随之改变,滑到最底部
//                        showIndex("*");
                    }
                    quickLocationRightTool.invalidate();
                }

                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
                oldSection = section;
            }
        });
    }

    /**
     * 获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
     *
     * @param sortKeyString
     * 数据库中读取出的sort key
     * @return 英文字母或者#
     */
    private String getSortKey(String sortKeyString) {
        String key = sortKeyString.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]")) {
            return key;
        }
        return "#";
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra("name", contacts.get(position).getName());
        intent.putExtra("phoneNum", contacts.get(position).getPhoneNumber());
        intent.setClass(getActivity(), ContactInformationActivity.class);
        getActivity().startActivity(intent);
    }

    public class LetterListViewListener implements QuickLocationRightTool.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(String s) {
            int num = 0;
            if (indexLetter.contains(s) || s.equals("*")) {
            int count = contactListView.getCount();
            for (int i = 0; i < count; i++) {
                if ("A".equals(s) || "#".equals(s))       //顶部
                    num = 0;
                else if ("*".equals(s))                      //底部
                    num = count;
                else if (contacts.get(i).getSortKey().toUpperCase().equals(s)) {
//                        || contacts.get(i).getSortKey().toUpperCase().equals(getNextIndexLetter(s))) {
                    break;                                     //首先判断是字母，字母的ascll值小于s是，滚动位置+1；如果有10个数据小于s，就滚到10处
                } else num += 1;
            }
            if (num < 2)
                contactListView.setSelectionFromTop(num, 0);
            else
                contactListView.setSelectionFromTop(num, 0);

//            String next = getNextIndexLetter(s);
//            if (s.equals("#") || indexLetter.contains(s))
//                showIndex(s);
//            else if (!s.equals("*"))
//                showIndex(next);
            }
        }
    }

//    private String getNextIndexLetter(String s) {
//        if (s.equals("Z")) return null;
//        if (s.matches("[A-Z]")) {
//            if (indexLetter.contains((++s.toCharArray()[0]) + ""))
//                return (++s.toCharArray()[0]) + "";
//            else
//                return getNextIndexLetter((++s.toCharArray()[0]) + "");
//        }
//        else return null;
//    }

    private Toast mToast;
    private void showIndex(String s) {
        TextView tv = new TextView(getActivity());
        tv.setText(s);
        tv.setMinWidth(100);
        tv.setBackgroundColor(0xa0a0a0a0);
        tv.setTextSize(50);
        tv.setGravity(Gravity.CENTER);
        if (mToast == null)
            mToast = new Toast(getActivity());
        mToast.setView(tv);
        mToast.show();
    }

}
